//index.js
//获取应用实例
var app = getApp()
var sta = require("../../utils/statistics.js");
var http = require("../../utils/httpHelper.js");
var util = require("../../utils/util.js");
Page({
  data: {
	  contents:{},
	  isShow:1,
    token:""
  },
  onShow:function (){
    sta();
  },
  onLoad: function () {
    var that = this;
    var token = wx.getStorageSync('token');
    
	  if(token){
      that.setData({
        token:token
      })
      console.log(token);
      http.request("/customer/index", {}, function (res) {
        if (res.data.code == 0) {
          that.setData({
            pages: res.data.data
          });
        }
      });
      http.request("/banner/getFooter", {}, function (res) {
        if (res.data.code == 0) {
          that.setData({ footerNav: res.data.data });
        }
      });
    }
    
  },
  showTab:function(event){
	  var v=parseInt(event.currentTarget.dataset.val);
	  this.setData({
		  isShow:v
	  });
  },
  goUrl:function(event){
    var url = event ? event.currentTarget.dataset.url : '';
	if(url.indexOf('pages/user/index')>0){
		return false;
	}
    util.goUrl(url,this);
  },
  userdata:function (){
      wx.navigateTo({url: "/pages/userdata/index"})
  },
  address: function (){
      wx.navigateTo({url:"/pages/select-address/index"});
  },
  
  order:function (){
    //订单
    wx.navigateTo({url: "/pages/order/index"})
  },
  keep:function () {
    //收藏
  },
  share:function (){
    //分享
  },
  getUser: function (userData) {
    var that = this;
    this.login();
  },
  login: function () {
    let that = this;
    let token = wx.getStorageSync('token');
    if (token) {
      http.request('/customer/check-token',{},function (res) {
          if (res.data.code != 0) {
            wx.removeStorageSync('token')
            that.login();
          } else {
            // 回到原来的地方放
            wx.navigateBack({});
          }
        }, -1)
      return;
    }
    let code = null;
    http.login().then((res) => {
      code = res.code;
      return http.getUserInfo();
    }).then((userInfo) => {
      //登录远程服务器
      http.request('/customer/wxapp_login',{ code: code, wxuser: userInfo.encryptedData, iv: userInfo.iv },function (res) {
          if (res.data.code == 0) {
            wx.setStorageSync('uid', res.data.data.uid);
            wx.setStorageSync('token', res.data.data.token);
            // 回到原来的页面
            wx.navigateBack({});
          } else {
            // 登录错误
            wx.hideLoading();
            wx.showModal({
              title: '提示',
              content: '无法登录，请重试' + res.data.errmsg,
              showCancel: false
            })
          }
        }, -1);
    }).catch((err) => {
      console.log(err)
    });
  }
})
